<?php
declare (strict_types=1);

namespace app\exam\logic\admin;

use app\common\model\ProductType;
use app\exam\model\admin\ModuleExamination;
use app\exam\model\admin\ModuleRollup;
use app\exam\model\admin\ModuleSpecial;
use app\exam\model\admin\Order as OrderModel;

/**
 * Class Order
 *
 * @package app\exam\logic\admin
 */
class Order extends OrderModel
{
    /**
     * 订单列表
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/5/6
     *
     * @param array $map
     * @return \think\Paginator
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(array $map)
    {
        return $this->with(['transaction', 'school', 'user', 'pdorder'])
            ->withJoin(['user', 'pdorder', 'transaction'], 'LEFT')
            ->where($map)
            ->order('update_time', 'DESC')
            ->paginate($this->getListRows())
            ->each(function ($item) {
                $item->product_title = $this->getProductTitle($item->product_id, $item->product_type_id);
            });
    }

    /**
     * 资源名称
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/5/6
     *
     * @param $product_id
     * @param $product_type_id
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function getProductTitle($product_id, $product_type_id)
    {
        $title = '【资源已被删除】';
        switch ($product_type_id) {
            // 公开考试
            case ProductType::getProductIdByKey('exam'):
                $exam  = ModuleExamination::withTrashed()->with(['module', 'paper'])->where('id', $product_id)->find();
                if ($exam) {
                    $title = $exam->module_title . ' - ' . $exam->title;
                }
                break;
            // 专项练习
            case ProductType::getProductIdByKey('special'):
                $exam  = ModuleSpecial::withTrashed()->with(['module'])->where('id', $product_id)->find();
                if ($exam) {
                    $title = $exam->module_title . ' - ' . $exam->title;
                }
                break;
            // 套卷练习
            case ProductType::getProductIdByKey('rollup'):
                $exam  = ModuleRollup::withTrashed()->with(['module'])->where('id', $product_id)->find();
                if ($exam) {
                    $title = $exam->module_title . ' - ' . $exam->title;
                }
                break;
            default:
                $ptitle = ProductType::getProductTitleById($product_type_id);
                $title  = $ptitle ? '购买【' . $ptitle . '】' : '未知';
                break;
        }

        return $title;
    }
}